package com.chen.base.utils;

import com.chen.root.enums.RejectedEnum;
import com.chen.base.property.ThreadPool;
import com.chen.base.property.ThreadPoolProperties;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.ArrayList;
import java.util.List;

/**
 * 线程池工具类
 * @Author: ChenJinLong
 * @DateTime: 2023/8/28 14:06
 **/
public class ThreadPoolUtil {

    /**
     * 构建ThreadPoolTaskExecutor
     * @param pool ThreadPool
     * @return ThreadPoolTaskExecutor
     */
    public static ThreadPoolTaskExecutor build(ThreadPool pool){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(pool.getCorePoolSize());
        executor.setMaxPoolSize(pool.getMaxPoolSize());
        executor.setQueueCapacity(pool.getQueueCapacity());
        executor.setKeepAliveSeconds(pool.getKeepAliveSeconds());
        executor.setThreadNamePrefix(pool.getName() + "-");
        // 拒绝策略
        Integer rejected = pool.getRefuseStrategy();
        executor.setRejectedExecutionHandler(RejectedEnum.getByCode(rejected));

        if (pool.getIsWait() != null){
            executor.setWaitForTasksToCompleteOnShutdown(pool.getIsWait());
        }
        executor.initialize();
        return executor;
    }

    /**
     * 获取线程池对象集
     * @return 线程池集
     */
    public static List<ThreadPoolTaskExecutor> getExecutors(){
        List<ThreadPoolTaskExecutor> list = new ArrayList<>();
        ThreadPoolProperties poolProperties = SpringContextHolder.getBean(ThreadPoolProperties.class);
        for (ThreadPool pool : poolProperties.getList()) {
            ThreadPoolTaskExecutor executor = SpringContextHolder.getBean(pool.getName());
            if (executor != null){
                list.add(executor);
            }
        }
        return list;
    }
}
